/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {AsyncStorage, DeviceEventEmitter, ScrollView, StyleSheet, Text, View} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import IparInput from "../../../custom/IparInput";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'


export default class UserEmailEdit extends Component {
    constructor(props) {
        super(props);

        this.state = {

            emailInput: '',
            userInfo: null,
            verificationCode: I18n.t('default.sendVerCode'),
            country: '',
            area_code: '',
        };
        this.emailInput = '';
        this.verCodeInput = '';

        this.iparNetwork = new IparNetwork();

    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this._timer && clearInterval(this._timer);
    }

    componentDidMount() {

        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                let parse = JSON.parse(result);

                CommonUtils.getAcyncInfo('country_area_code')
                    .then((result) => {
                        this.setState({
                            userInfo: parse,
                            country: parse.country,
                            area_code: result,
                        });
                    });

            });


    }

    // /*编辑用户联系Email*/
    // editUserInfo() {
    // 	let formData = new FormData();
    // 	formData.append("user_id", this.state.userID);
    // 	formData.append("email", this.state.emailInput);
    // 	formData.append("code", this.state.verCodeInput);
    //
    //
    // 	this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'addContact', formData)
    // 		.then((result) => {
    // 			this.setState({showDialog: false});
    // 			if (result.code === 200) {
    // 				console.log(result.data);
    // 				new CommonUtils().saveUserInfo(result.data);
    // 				this.props.navigator.popToTop();
    // 				DeviceEventEmitter.emit('toast', I18n.t('default.success'))
    // 			}
    // 		}).catch((error) => {
    // 		this.setState({showDialog: false});
    // 		console.log(error)
    // 	})
    // }

    /**
     * 修改密码或者email
     * */
    editPassInfo() {

        let isEmail = this.props.type === 0;

        let formData = new FormData();
        let userInfo = this.state.userInfo;
        if (isEmail) {
            formData.append("user_id", userInfo.main_user_id);
        }
        formData.append("area_code", this.state.area_code);
        formData.append("mobile", this.props.mobile);
        formData.append("code", this.verCodeInput);
        formData.append(isEmail ? 'email' : "user_pass", this.emailInput);


        let _url = isEmail ? 'updateEmail' : 'findPassword';


        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + _url, formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    if (isEmail) {
                        userInfo.email = this.emailInput;
                        CommonUtils.saveUserInfo(userInfo);
                    }
                    if (isEmail) {
                        this.props.navigator.popToTop();
                    } else {
                        this.props.navigator.pop();
                    }
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'))
                } else if (result.code === 444) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.verCodeError'))
                }
                console.log(result)
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error)
            })
    }


    /**
     * 获取验证码
     * type register activation bind upmobile updatePassword upgrade
     */
    getSmsInfo() {
        if (this._index > 0) {
            return;
        }
        CommonUtils.showLoading();

        let _mobile = this.props.mobile;

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'sms?',
            'phone=' + _mobile + '&type=update&country=' + this.state.area_code)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    this.countTime();
                    DeviceEventEmitter.emit('toast', I18n.t('toast.sendVerCodeSuccess'));
                }
            }).catch((error) => {
            CommonUtils.dismissLoading();

            console.log(error)
        })
    }


    /*获取验证码时间*/
    countTime() {
        this._index = 60;
        this._timer = setInterval(() => {
            this.setState({verificationCode: this._index-- + ' s'});
            if (this.state.verificationCode <= 0 + ' s') {
                this._timer && clearInterval(this._timer);
                this.setState({verificationCode: I18n.t('toast.againGetCode')});
            }
        }, 1000);

    }


    render() {
        let isEmail = this.props.type === 0;
        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                />

                <KeyboardAwareScrollView>
                    <View style={[StyleUtils.flex, {paddingLeft: 16, paddingRight: 16}]}>
                        {ViewUtils.getTitleView(isEmail ? I18n.t('default.email') : I18n.t('default.password'), I18n.t('default.editYourAccount'))}

                        <Text
                            style={[styles.numberTv, StyleUtils.smallFont]}>{new CommonUtils().phoneEncryption(this.props.mobile)}</Text>


                        <View style={[StyleUtils.justifySpace, StyleUtils.marginTop]}>

                            <IparInput
                                style={{
                                    marginTop: 0,
                                    flex: 1,
                                }}
                                keyboardType={'number-pad'}
                                onChangeText={(text) => this.verCodeInput = text}
                                placeholder={I18n.t('toast.enterVerification')}/>


                            {ViewUtils.getButton(this.state.verificationCode, () => this.getSmsInfo(), {
                                flex: 1,
                                marginLeft: 8
                            }, {fontSize: 14})}

                        </View>


                        <IparInput
                            isPassword={!isEmail}
                            onChangeText={(text) => this.emailInput = text}
                            placeholder={this.props.email ? this.props.email : I18n.t('default.interNewPass')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => this.onclick(), StyleUtils.marginTop)}
                    </View>
                </KeyboardAwareScrollView>
            </View>
        );
    }

    /*onPressBtn btn 点击*/
    onclick() {


        if (this.verCodeInput.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.interVerCode'));
            return;
        }
        if (this.emailInput.trim() === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.interNewPass'));
            return;
        }

        if (this.props.type === 0 && !CommonUtils.checkEmail(this.emailInput.trim())) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.emailFormatError'));
            return;
        }

        if (this.props.type === 1 && !CommonUtils.isPassword(this.emailInput)) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.isNotPassword'));
            return;
        }

        CommonUtils.showLoading();

        this.editPassInfo();

    }

}

const styles = StyleSheet.create({
    numberTv: {
        fontSize: 17,
        color: 'black',
        marginTop: 14,
    }
});
